package cn.vihub.controller;

import cn.vihub.utils.Result;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

// 解决跨域问题
@CrossOrigin
@RestController
@RequestMapping("shop-file/img")
public class ImgController {


    // 创建一个minio的客户端链接
    @Autowired
    private MinioClient minioClient;

    @Value("${minio.imgurl}")
    private String minioImgurl;

    @PostMapping
    public Result<Object> upload(MultipartFile file) throws Exception {

        // 获取原来的文件的后缀
        String[] split = file.getOriginalFilename().split("\\.");
        String ext = split[split.length - 1];
        String fileName = UUID.randomUUID().toString()+"."+ext;

        minioClient.putObject(PutObjectArgs.builder().bucket("2301a")
                .object(fileName).stream(
                        file.getInputStream(), file.getSize(), -1).build());

        // http://127.0.0.1:9000/2301a/f0ddb049-e7c7-484f-9472-951887580e41.png

        String fileUrl = minioImgurl + "/" + fileName;

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("fileName", fileName);
        hashMap.put("fileUrl", fileUrl);
        return Result.success(hashMap);

    }
}
